import Vue from "vue";
import Router from "vue-router";
import Home from "@/components/Home/index";
import Login from "@/components/Login/index";
import Settings from "@/components/Settings/index";
import Article from "components/Article/index";
import Index from "@/App";
import NotFound from "components/NotFound";
import { isLogin } from "../utils/authService";

Vue.use(Router);

const router = new Router({
  mode: "history",

  // scrollBehavior: true,
  routes: [
    {
      path: "/",
      name: "home",
      component: Home
    },
    {
      path: "/login",
      name: "login",
      component: Login,
      meta: {
        requiresNotAuth: true
      }
    },
    {
      path: "/settings",
      name: "settings",
      component: Settings,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: "/article/:aid",
      name: "article",
      component: Article,
      meta: {
        goTop: true
      }
    },
    {
      path: "/apps",
      name: "apps",
      component: Index
    },
    {
      path: "*",
      component: NotFound
    }
  ]
});

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.goTop)) {
    window.scroll(0, 0);
  }

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isLogin()) {
      return next({ path: "/login" });
    }
  }
  if (to.matched.some(record => record.meta.requiresNotAuth)) {
    if (isLogin()) {
      return next({ path: "/" });
    }
  }
  next();
});
export default router;
